package cn.byapps.master.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.byapps.master.entity.TaskInfo;
import cn.byapps.master.service.TaskInfoService;
import cn.byapps.master.vo.Result;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("task")
@CrossOrigin
@Slf4j
public class TaskInfoController {
	@Value("${upload.url}")
	private String tempURL;
	@Value("${upload.path}")
	private String path;

	@Autowired
	private TaskInfoService taskService;

	@GetMapping
	public Result list() {
		List<TaskInfo> items = taskService.list();
		Map<String, Object> map = new HashMap<>();
		map.put("items", items);
		map.put("total", items.size());
		return new Result(1, "1", "1", map);
	}

	@DeleteMapping("{id}")
	public Result delete(@PathVariable String id) {
		taskService.deleteById(id);
		Map<String, Object> map = new HashMap<>();
		return new Result(1, "1", "1", map);
	}

	//OPTIONS
	@PostMapping
	public Result add(TaskInfo item, MultipartFile file, HttpServletRequest req) throws Exception, IOException {

		log.info(item.toString());
		if (file != null) {
			File f = new File(path);
			if (!f.exists())
				f.mkdirs();
			file.transferTo(new File(path, file.getOriginalFilename()));
			item.setImgPath(tempURL + file.getOriginalFilename());
		}
		taskService.save(item);
		return new Result(1, "1", "1", null);
	}

}
